package com.cleanvegetable.company.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cleanvegetable.common.cache.RedisCacheManager;
import com.cleanvegetable.common.exception.ServiceException;
import com.cleanvegetable.company.dto.CompanyDTO;
import com.cleanvegetable.company.dto.CompanyQueryDTO;
import com.cleanvegetable.company.entity.Company;
import com.cleanvegetable.company.mapper.CompanyMapper;
import com.cleanvegetable.company.service.CompanyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 公司信息服务实现类 - 实现具体的业务逻辑
 * @author system
 */
@Slf4j
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, Company> implements CompanyService {

    /**
     * Redis缓存管理器
     */
    @Resource
    private RedisCacheManager redisCacheManager;

    /**
     * Redis缓存key前缀
     */
    private static final String CACHE_KEY_PREFIX = "company:";

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer addCompany(CompanyDTO companyDTO) {
        // 记录开始日志
        log.info("新增公司信息开始，参数：{}", companyDTO);
        
        // 参数校验
        if (companyDTO == null) {
            throw new ServiceException("参数不能为空");
        }
        
        // 检查编号是否重复
        LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Company::getCode, companyDTO.getCode());
        if (this.count(queryWrapper) > 0) {
            throw new ServiceException("公司编号已存在");
        }
        
        // DTO转换为实体
        Company company = new Company();
        BeanUtils.copyProperties(companyDTO, company);
        
        // 保存数据
        this.save(company);
        
        // 清除缓存
        redisCacheManager.deleteByPrefix(CACHE_KEY_PREFIX);
        
        // 记录结束日志
        log.info("新增公司信息结束，结果：{}", company.getId());
        return company.getId();
    }

    @Override
    public PageInfo<CompanyDTO> pageQuery(CompanyQueryDTO queryDTO) {
        // 记录开始日志
        log.info("分页查询公司信息开始，参数：{}", queryDTO);
        
        // 构建缓存key
        String cacheKey = buildCacheKey(queryDTO);
        
        // 从缓存获取数据，如果不存在则从数据库查询
        return redisCacheManager.getOrLoad(cacheKey, () -> {
            // 构建查询条件
            LambdaQueryWrapper<Company> queryWrapper = new LambdaQueryWrapper<>();
            // 客户标识
            queryWrapper.eq(queryDTO.getIsClient() != null, Company::getIsClient, queryDTO.getIsClient());
            // 供应商标识
            queryWrapper.eq(queryDTO.getIsVendor() != null, Company::getIsVendor, queryDTO.getIsVendor());
            // 状态
            queryWrapper.eq(queryDTO.getStatus() != null, Company::getStatus, queryDTO.getStatus());
            // 编号模糊查询
            queryWrapper.like(StringUtils.hasText(queryDTO.getCode()), Company::getCode, queryDTO.getCode());
            // 名称模糊查询
            queryWrapper.like(StringUtils.hasText(queryDTO.getCompanyName()), Company::getCompanyName, queryDTO.getCompanyName());
            // 按创建时间倒序
            queryWrapper.orderByDesc(Company::getCreateTime);
            
            // 设置分页参数
            PageHelper.startPage(queryDTO.getPageNum(), queryDTO.getPageSize());
            // 执行查询
            List<Company> list = this.list(queryWrapper);
            
            // 实体转换为DTO
            List<CompanyDTO> dtoList = list.stream().map(company -> {
                CompanyDTO dto = new CompanyDTO();
                BeanUtils.copyProperties(company, dto);
                return dto;
            }).collect(Collectors.toList());
            
            // 封装分页信息
            PageInfo<CompanyDTO> pageInfo = new PageInfo<>(dtoList);
            
            // 记录结束日志
            log.info("分页查询公司信息结束，结果数量：{}", pageInfo.getTotal());
            return pageInfo;
        });
    }
    
    /**
     * 构建缓存key
     * @param queryDTO 查询条件DTO
     * @return 缓存key字符串
     */
    private String buildCacheKey(CompanyQueryDTO queryDTO) {
        StringBuilder sb = new StringBuilder(CACHE_KEY_PREFIX);
        // 添加分页信息
        sb.append("page:")
          .append(queryDTO.getPageNum())
          .append(":")
          .append(queryDTO.getPageSize())
          .append(":");
        
        // 添加查询条件
        if (queryDTO.getIsClient() != null) {
            sb.append("client:").append(queryDTO.getIsClient());
        }
        if (queryDTO.getIsVendor() != null) {
            sb.append("vendor:").append(queryDTO.getIsVendor());
        }
        if (queryDTO.getStatus() != null) {
            sb.append("status:").append(queryDTO.getStatus());
        }
        if (StringUtils.hasText(queryDTO.getCode())) {
            sb.append("code:").append(queryDTO.getCode());
        }
        if (StringUtils.hasText(queryDTO.getCompanyName())) {
            sb.append("name:").append(queryDTO.getCompanyName());
        }
        
        return sb.toString();
    }
} 